package com.taldh.algorithm.treenode;

import com.taldh.algorithm.base.TreeNode;
import org.junit.Assert;
import org.junit.Test;

/*
*
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
*/
public class MinDepth {

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if ((root.left == null) && (root.right == null)) {
            return 1;
        }

        int minDepth = Integer.MAX_VALUE;
        if (root.left != null) {
            minDepth = Math.min(minDepth(root.left), minDepth);
        }
        if (root.right != null) {
            minDepth = Math.min(minDepth(root.right), minDepth);
        }

        return minDepth+1;
    }

    @Test
    public void test() {
        //3,9,20,null,null,15,7
        TreeNode root = new TreeNode(3,new TreeNode(9),
                new TreeNode(20,new TreeNode(15), new TreeNode(7)));
        Assert.assertEquals(2,
                minDepth(root));
    }

    @Test
    public void test1() {
        //1,2
        TreeNode root = new TreeNode(1, null, new TreeNode(2));
        Assert.assertEquals(2, minDepth(root));
    }

}